var express = require('express');
var router = express.Router();
var {movie_model,user_model} = require("../utils/model")
var {aesEncrypt} = require("../utils")
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get("/demo",(req,res)=>{
   res.send("users - users - demo - yyds ")
})

router.all("/getonedata",(req,res)=>{
  res.json({
    code:200,
    msg:"获取数据成功",
    result:null
  })
})


// 注册  form 
router.post("/zhuce",(req,res)=>{
  var body = req.body ;
  console.log(body);
  user_model.findOne({
    username:body.username 
  })
  .then(data=>{
    if(data){
       res.send(`<script>alert('用户名已经被注册,请重新注册');location.href='/register';</script>`)
    }else{
      //可以注册
      body.time = new Date();
      user_model.insertMany(body)
      .then(result=>{
        res.send(`<script>alert('注册成功,即将跳转登录');location.href='/login?username=${aesEncrypt(body.username)}';</script>`)
      })
    }
  })
  .catch(err=>{
    res.send(`<script>alert('服务器异常');location.reload();</script>`)
    // res.json({
    //   code:500,
    //   msg:"服务器异常",
    //   err
    // })
  })
})

// 注册2
router.post("/register",(req,res)=>{
  var body = req.body;
  user_model.findOne({
    username:body.username
  })
  .then(data=>{
    if(data){
      res.json({
        code:401,
        msg:"用户名已经被注册,请重新注册",
        data
      })
    }else{
      body.time = new Date()
      user_model.insertMany(body)
      .then(result=>{
        res.json({
          code:200,
          msg:"注册成功",
          result
        })
      })
    }
  })
  .catch(err=>{   
    res.json({
      code:500,
      msg:"服务器异常",
      err
    })
  })
})


// login
router.post("/login",(req,res)=>{
  var body = req.body;
  user_model.findOne({
    username:body.username
  })
  .then(data=>{
    if(data){
      if(data.password==body.password){
         // 记录登录的状态 session 
         req.session.username = body.username;
         req.session.userinfo = data; 
         res.redirect("/") 
      }else{
        res.send(`<script>alert('密码错误');location.href='/login';</script>`)
      }
    }else{
      res.send(`<script>alert('用户名不存在');location.href='/login';</script>`)
    }
  })
  .catch(err=>{
    res.send(`<script>alert('服务器异常');location.reload();</script>`)

  })
})
module.exports = router;
